class TagsController < ApplicationController
  before_filter :find_tag, :except => [ :index ]
  before_filter :login_required, :only => [ :destroy, :delete ]

  # maps to /tags - named route of tags_url
  # HTTP verb: GET  
  def index
    @tags = Tag.find(:all, :order => 'name')

    respond_to do |format|
      format.html
      format.xml  { render :xml => @tags.to_xml }
    end
  end

  # maps to /tags/:id - named route of tag_url(tag_object)
  # HTTP verb: GET
  def show
    respond_to do |format|
      format.html {
        @pager = ::Paginator.new(@tag.taggings.size, AppConstants::LIMIT) do |offset, per_page|
          Article.find_per_tag(@tag, offset, per_page)
        end
        @page = @pager.page(params[:page])
        @num_pages = @tag.taggings.size/AppConstants::LIMIT + 1
      }
      format.xml  {
        offset = (params[:page] and params[:page].to_i > 1) ?
                 (params[:page].to_i - 1)*AppConstants::LIMIT : 0
        @articles = Article.find_per_tag(@tag, offset, AppConstants::LIMIT)
        render :xml => @articles.to_xml(:except => [:body, :user_id])
      }
    end  
  end

  def delete
  end

  def destroy
    @tag.destroy if request.delete?
    redirect_to tags_url
  end
  
  protected
    def find_tag
      @tag = Tag.find(params[:id])
    end

    # only admin can delete tags
    def authorized?
      current_user.login == 'admin'
    end
end
